package controller.permission;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import bean.Permission;
import service.PermissionService;
import service.impl.PermissionServiceImpl;
import utils.ResponseBodyUtil;


public class LoadData extends HttpServlet {
	private static final long serialVersionUID = 1L;

	private PermissionService permissionService = new PermissionServiceImpl();
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		List<Permission> permissions = new ArrayList<Permission>();
		
//		Permission root = new Permission();
//		root.setName("�����ڵ�");
//		
//		Permission child = new Permission();
//		child.setName("�ӽڵ�");
//		
//		root.getChildren().add(child);
//		permissions.add(root);
		
		// ��ȡ���νṹ����
		/*
		Permission root = permissionService.queryRootPermission();		
		
		List<Permission> childPermissions = permissionService.queryChildPermissions(root.getId());
		
		for ( Permission childPermission : childPermissions ) {
			List<Permission> childChildPermissions = permissionService.queryChildPermissions(childPermission.getId());
			childPermission.setChildren(childChildPermissions);
		}
		
		root.setChildren(childPermissions);
		
		permissions.add(root);
		*/
		
		// �ݹ��ѯ����
		/*
		Permission parent = new Permission();
		parent.setId(0);
		queryChildPermissions(parent);
		//permissions.
		return parent.getChildren();
		*/
		
		// ��ѯ���е��������
		List<Permission> ps = permissionService.queryAll();
		
		/*
		for ( Permission p : ps ) {
			// �ӽڵ�
			Permission child = p;
			if ( p.getPid() == 0 ) {
				permissions.add(p);
			} else {
				for ( Permission innerPermission : ps ) {
					if ( child.getPid().equals(innerPermission.getId()) ) {
						// ���ڵ�
						Permission parent = innerPermission;
						// ��ϸ��ӽڵ�Ĺ�ϵ
						parent.getChildren().add(child);
						break;
					}
				}
			}
		}
		*/
		
		Map<Integer, Permission> permissionMap = new HashMap<Integer, Permission>();
		for (Permission p : ps) {
			permissionMap.put(p.getId(), p);
		}
		for ( Permission p : ps ) {
			Permission child = p;
			if ( child.getPid() == 0 ) {
				permissions.add(p);
			} else {
				Permission parent = permissionMap.get(child.getPid());
				parent.getChildren().add(child);
			}
		}
		
		ResponseBodyUtil.sendJsonObject(response, permissions);
	}

}
